package scau.erps.view.base;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI;

import scau.erps.app.Erps;
import scau.erps.entity.Balancesheet;
import scau.erps.entity.Comprehensivefee;
import scau.erps.entity.Extrascore;
import scau.erps.entity.Factory;
import scau.erps.entity.FreeMarket;
import scau.erps.entity.Incomestatement;
import scau.erps.entity.Line;
import scau.erps.entity.Loan;
import scau.erps.entity.Material;
import scau.erps.entity.Product;
import scau.erps.entity.Research;
import scau.erps.entity.Sand;
import scau.erps.entity.Score;
import scau.erps.entity.Store;
import scau.erps.entity.Team;
import scau.erps.entity.TeamOrder;
import scau.erps.service.BalancesheetService;
import scau.erps.service.ComprehensivefeeService;
import scau.erps.service.ExtrascoreService;
import scau.erps.service.FactoryService;
import scau.erps.service.FreeMarketService;
import scau.erps.service.IncomestatementService;
import scau.erps.service.LineService;
import scau.erps.service.LoanService;
import scau.erps.service.MaterialService;
import scau.erps.service.ProductService;
import scau.erps.service.ResearchService;
import scau.erps.service.SandService;
import scau.erps.service.ScoreService;
import scau.erps.service.StoreService;
import scau.erps.service.TeamOrderService;
import scau.erps.service.impl.BalancesheetServiceImpl;
import scau.erps.service.impl.ComprehensivefeeServiceImpl;
import scau.erps.service.impl.ExtrascoreServiceImpl;
import scau.erps.service.impl.FactoryServiceImpl;
import scau.erps.service.impl.FreeMarketServiceImpl;
import scau.erps.service.impl.IncomestatementServiceImpl;
import scau.erps.service.impl.LineServiceImpl;
import scau.erps.service.impl.LoanServiceImpl;
import scau.erps.service.impl.MaterialServiceImpl;
import scau.erps.service.impl.ProductServiceImpl;
import scau.erps.service.impl.ResearchServiceImpl;
import scau.erps.service.impl.SandServiceImpl;
import scau.erps.service.impl.ScoreServiceImpl;
import scau.erps.service.impl.StoreServiceImpl;
import scau.erps.service.impl.TeamOrderServiceImpl;
import scau.erps.util.CalculateQuarter;
import scau.erps.view.SandPanel;
import scau.erps.view.system.team.MyOrderBiddingDialog;

/**
 * 决策面板
 *    主窗口左侧步骤按钮
 * @author DCJ
 *
 */
public class DecisionPanel extends ButtonPanel {
	private static final long serialVersionUID = 1L;
	private SandPanel dashBoardPanel;
	private JPanel beginOfYearPanel, middleOfYearPanel, endOfYearPanel;
	private SchedulePanel schedule;
	private Team team = Erps.getCurrentTeam();
	private SandService sandService = Erps.getIocInstance().get(
			SandServiceImpl.class);
	private LoanService loanService = Erps.getIocInstance().get(
			LoanServiceImpl.class);
	private MaterialService materialService = Erps.getIocInstance().get(
			MaterialServiceImpl.class);
	private FactoryService factoryService = Erps.getIocInstance().get(
			FactoryServiceImpl.class);
	private LineService lineService = Erps.getIocInstance().get(
			LineServiceImpl.class);
	private ProductService productService = Erps.getIocInstance().get(
			ProductServiceImpl.class);
	private IncomestatementService incomestatementService = Erps
			.getIocInstance().get(IncomestatementServiceImpl.class);
	private ResearchService researchService = Erps.getIocInstance().get(
			ResearchServiceImpl.class);

	public DecisionPanel(SandPanel dashBoardPanel) {
		this.dashBoardPanel = dashBoardPanel;
		JPanel decisionPanel = new JPanel();
		decisionPanel.setLayout(new BorderLayout());
		JPanel panel = new JPanel(new BorderLayout());
		schedule = new SchedulePanel();
		panel.add(schedule, BorderLayout.NORTH);
		panel.add(getBeginOfYearPanel(), BorderLayout.CENTER);
		decisionPanel.add(panel, BorderLayout.NORTH);
		decisionPanel.add(getMiddleOfYearPanel(), BorderLayout.CENTER);
		decisionPanel.add(getEndOfYearPanel(), BorderLayout.SOUTH);
		this.add(decisionPanel);
	}

	/**
	 * 年初决策面板
	 * 
	 * @return
	 */
	private JPanel getBeginOfYearPanel() {
		if (beginOfYearPanel == null) {
			beginOfYearPanel = new JPanel();
		}
		beginOfYearPanel.setBorder(BorderFactory.createTitledBorder("年初决策"));
		beginOfYearPanel.setPreferredSize(new Dimension(320, 70));
		beginOfYearPanel.add(btn[0]);
		beginOfYearPanel.add(btn[1]);
		beginOfYearPanel.add(btn[2]);
		beginOfYearPanel.add(btn[3]);
		return beginOfYearPanel;
	}

	/**
	 * 年中决策面板
	 * 
	 * @return
	 * @author 郑剑川
	 */
	private JPanel getMiddleOfYearPanel() {
		if (middleOfYearPanel == null) {
			middleOfYearPanel = new JPanel();
		}
		JPanel[] panel = new JPanel[8];
		for (int i = 0; i < panel.length; i++) {
			panel[i] = new JPanel(new FlowLayout(FlowLayout.LEFT));
		}
		panel[0].add(new JLabel("(1)"));
		panel[0].add(btn[4]);
		panel[0].add(btn[5]);
		panel[0].add(btn[6]);
		panel[1].add(new JLabel("(2)"));
		panel[1].add(btn[7]);
		panel[1].add(btn[8]);
		panel[2].add(new JLabel("(3)"));
		panel[2].add(btn[9]);
		panel[2].add(btn[10]);
		panel[2].add(btn[11]);
		panel[3].add(new JLabel("(4)"));
		panel[3].add(btn[12]);
		panel[3].add(btn[13]);
		panel[4].add(new JLabel("(5)"));
		panel[4].add(btn[14]);
		panel[4].add(btn[15]);
		panel[4].add(btn[16]);
		panel[5].add(new JLabel("(6)"));
		panel[5].add(btn[17]);
		panel[5].add(btn[18]);
		panel[6].add(new JLabel("(7)"));
		panel[6].add(btn[19]);
		panel[6].add(btn[20]);
		panel[7].add(new JLabel("(8)"));
		panel[7].add(btn[21]);
		panel[7].add(btn[22]);
		middleOfYearPanel.setBorder(BorderFactory.createTitledBorder("年中决策"));
		middleOfYearPanel.setLayout(new GridLayout(8, 1));
		middleOfYearPanel.setPreferredSize(new Dimension(320, 340));
		for (int i = 0; i < panel.length; i++) {
			middleOfYearPanel.add(panel[i]);
		}
		return middleOfYearPanel;
	}

	/**
	 * 年末决策面板
	 * 
	 * @return
	 */
	private JPanel getEndOfYearPanel() {
		if (endOfYearPanel == null) {
			endOfYearPanel = new JPanel();
		}
		endOfYearPanel.setBorder(BorderFactory.createTitledBorder("年末决策"));
		endOfYearPanel.setLayout(new GridLayout(3, 1));
		endOfYearPanel.setPreferredSize(new Dimension(320, 145));
		JPanel[] panel = new JPanel[3];
		for (int i = 0; i < panel.length; i++) {
			panel[i] = new JPanel(new FlowLayout(FlowLayout.LEFT));
		}
		panel[0].add(new JLabel("(1)"));
		panel[0].add(btn[23]);
		panel[0].add(btn[24]);
		panel[0].add(btn[25]);
		panel[1].add(new JLabel("(2)"));
		panel[1].add(btn[26]);
		panel[1].add(btn[27]);
		panel[1].add(btn[28]);
		panel[2].add(new JLabel("(3)"));
		panel[2].add(btn[29]);
		panel[2].add(btn[30]);
		panel[2].add(btn[31]);
		for (int i = 0; i < panel.length; i++) {
			endOfYearPanel.add(panel[i]);
		}
		return endOfYearPanel;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		/*** 年度规划 ****/
		if (e.getSource() == btn[0]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 1) {
				sandService.clearCost(team.getId());
				String message = "开始讨论本年度策略,"+"\n"+"请在数字仪表盘查看决策所需信息。";
				JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.INFORMATION_MESSAGE);
				this.changeStep();
				this.dashBoardPanel.setDashBoardData(1);
			}

		}
		/*** 支付应付税 ****/
		else if (e.getSource() == btn[1]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 2) {
				int team_Id = team.getId();				
				int tax = incomestatementService.payTax(team_Id);				
				String message = "需支付去年应付税" + tax + "M，"+"\n"+"请从沙盘现金区域取"+tax+"M放入所得税区域";
				JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.INFORMATION_MESSAGE);
				this.changeStep();
				this.dashBoardPanel.setDashBoardData(2);
			}
		}

		/*** 订单竞价 ****/
		else if (e.getSource() == btn[2]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 3) {
				if (Erps.getLimit().getStep()==2) 				
					JOptionPane.showMessageDialog(null, "订单竞价尚未开始，请等待","提示",JOptionPane.INFORMATION_MESSAGE);
				else {
					new MyOrderBiddingDialog();
					this.dashBoardPanel.setDashBoardData(3);
					this.changeStep();
				}
			}
		}
		/*** 登记订单 ****/
		else if (e.getSource() == btn[3]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 4) {
				if (Erps.getLimit().getStep()==3)
					JOptionPane.showMessageDialog(null, "尚有小组未完成竞价或订单匹配未完成，请稍等。","提示",JOptionPane.INFORMATION_MESSAGE);
				else{
				TeamOrderService orderService = Erps.getIocInstance().get(TeamOrderServiceImpl.class);
				int n = orderService.recordOrders();
				Sand sand = sandService.getSandByTeam(team.getId());
				int m = sand.getAdvertisingFee();
				String message = n+ "张订单登记成功，请在我的业务中查看订单详细信息"+"\n"+"请从沙盘现金区域取竞价费用"+m+"M放入广告费区域。";
				JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.INFORMATION_MESSAGE);
				this.changeStep();
				this.dashBoardPanel.setDashBoardData(4);
				}
			}
		}

		/*** 更新短贷 ****/
		else if (e.getSource() == btn[4]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 5) {
				String message = "请将沙盘短贷和高利贷区域贷款向现金方向移动一格；"+"\n"+"系统盘面将在下一步自动更新。";
				JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.INFORMATION_MESSAGE);
				this.changeStep();
			}
		}

		/*** 偿还短贷 ****/
		else if (e.getSource() == btn[5]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 6) {
				int team_Id = team.getId();
				List<Loan> shortLoans = loanService.getReturnLoans(team_Id, "短贷");
				List<Loan> highLoans = loanService.getReturnLoans(team_Id,"高利贷");
				int n = loanService.getSizeOfShortLoanByTeam(team_Id);
				int amount =  loanService.getAmountOfShortLoanByTeam(team_Id);
				int interest = loanService.getInterestOfShortLoanByTeam(team_Id);				
				int cash = Erps.getSand().getCash();
				if (cash >= (amount + interest)) {
					loanService.repayShortLoan(shortLoans);
					loanService.repayShortLoan(highLoans);
					String message = "已成功偿还短贷、高利贷"+n+"笔，共计金额"+amount+"M。"+"\n"+ "共支付利息"+interest+ "M"+"\n"+"请进行沙盘操作。";
					JOptionPane.showMessageDialog(null, message, "提醒",JOptionPane.INFORMATION_MESSAGE);
					this.changeStep();
					this.dashBoardPanel.setDashBoardData(6);
					this.dashBoardPanel.setShortLoanData();
					this.dashBoardPanel.setHighLoanData();
				} else {
					JOptionPane.showMessageDialog(null,"当前现金不足偿还应还短贷、高利贷以及利息，请先融资！", "警告",	JOptionPane.WARNING_MESSAGE);
				}
			}
		}

		/*** 申请短贷 ****/
		else if (e.getSource() == btn[6]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 7) {
				List<String> list = new ArrayList<String>();
				int availiable=loanService.getAvailiable();
				if(availiable>=20){
					for(int i=20;i<=availiable;i=i+20){
						list.add(i+"");
					}
				    String[] amount = new String[list.size()]; 
				    list.toArray(amount);
					String s = (String) JOptionPane.showInputDialog(null,
							"目前可贷款数量:"+availiable+"M\n"+"请选择贷款额度:\n"+"若可贷款数量小于20M，无法申请短贷", 
							"申请短贷", JOptionPane.PLAIN_MESSAGE, null, amount, null);
					if (s != null) {
						int a = Integer.parseInt(s);
						if(loanService.ifAvailable(a)){
							loanService.applyShortLoan(a);
							String message1= a+"M短期贷款申请成功，请前往银行领取现金！";
							JOptionPane.showMessageDialog(null, message1, "提醒",	JOptionPane.INFORMATION_MESSAGE);
						}else{
							JOptionPane.showMessageDialog(null, "所贷金额+已有贷款超过上年所有者权益的2倍，请调整申请金额。", "警告",JOptionPane.WARNING_MESSAGE);
						}					
					}
				}else{
					JOptionPane.showMessageDialog(null, "可申请短贷额度小于20M，不能申请。", "提醒",JOptionPane.INFORMATION_MESSAGE);
				}
				this.changeStep();
				this.dashBoardPanel.setDashBoardData(7);
				this.dashBoardPanel.setShortLoanData();
			}
		}

		/*** 更新应付款 ****/
		else if (e.getSource() == btn[7]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 8) {
				JOptionPane.showMessageDialog(null, "请将沙盘应付款向现金方向移动一格；"+"\n"+"系统盘面将在下一步自动更新。", "提示",JOptionPane.INFORMATION_MESSAGE);
				this.changeStep();
				this.dashBoardPanel.setShortLoanData();    //更新短贷面板 防止工作人员审批较慢导致的面板数据不符
				this.dashBoardPanel.setDashBoardData(9);//更新现金区域
			}
		}

		/*** 归还应付款 ****/
		else if (e.getSource() == btn[8]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 9) {				
				List<Material> materialOrderList = materialService.getPayMaterialOrder(team.getId(), Erps.getSand().getTime());
				int tot = 0;
				int pay = 0;
				for (Material material : materialOrderList) {
					if (material.getStatus().equals("已入库"))
						pay = pay + material.getNumber();
					if (!material.getGetTime().equals(material.getPayTime()))
						tot++;
				}
				if (materialService.payMaterialOrder(team.getId(), Erps.getSand().getTime())) { // 当前现金可以支付本季度应付款
					String message = "需偿还" + tot + "笔原材料订单应付款共计" + pay + " M。"+"\n"+"请取走沙盘应付款1Q位置的红币，并从现金区域取"+pay+"M交至银行。";
					JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.INFORMATION_MESSAGE);
					this.changeStep();
					this.dashBoardPanel.setDashBoardData(9);
					this.dashBoardPanel.setPayableData();
				} else {
					String message = "本季度需偿还应付款共计"+pay+"M。" + " \n" + "当前现金不足，请先进行融资操作";
					JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.INFORMATION_MESSAGE);
				}
			}
		}

		/*** 更新原材料订单 ****/
		else if (e.getSource() == btn[9]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 10) {
				JOptionPane.showMessageDialog(null, "请将沙盘原材料订单向原材料仓库区域移动一格;"+"\n"+"系统盘面将在下一步自动更新。", "提示",JOptionPane.INFORMATION_MESSAGE);
				this.changeStep();
			}
		}

		/*** 原材料订单入库 ****/
		else if (e.getSource() == btn[10]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 11) {
				int pay = materialService.updateStore(team.getId(), Erps.getSand().getTime());
				if (pay >= 0) {
					Map<String,Integer> map = materialService.getAmountOfGet(team.getId(), Erps.getSand().getTime());
					String message = "共有 "+map.get("Total")+"笔原材料订单需要入库。"+"\n"+"M1入库"+map.get("M1")+"个，M2入库"+map.get("M2")+"个，M3入库"+map.get("M3")+
							"个，M4入库"+map.get("M4")+"个。"+"\n" +"共需支付费用"+pay+"M";
					JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.INFORMATION_MESSAGE);
					this.changeStep();
					this.dashBoardPanel.setDashBoardData(11);
					this.dashBoardPanel.setPayableData();
				} else {
					JOptionPane.showMessageDialog(null, "当前现金不足以支付货款，请先融资！","警告", JOptionPane.WARNING_MESSAGE);
				}
			}
		}

		/*** 下原材料订单 ****/
		else if (e.getSource() == btn[11]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 12) {
				int flag=JOptionPane.showConfirmDialog(null, "本季度是否下原材料订单","提示",JOptionPane.YES_NO_OPTION);
				if (flag==JOptionPane.YES_OPTION){
					new MaterialOrderDialog(this);
				}
				this.changeStep();
			   
			}
		}
		/*** 更新生产 ****/
		else if (e.getSource() == btn[12]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 13) {
				JOptionPane.showMessageDialog(null, "请将沙盘生产区域在制品向产成品库方向移动一格;"+"\n"+"系统将在下一步自动更新。", "提示",
						JOptionPane.INFORMATION_MESSAGE);
				this.changeStep();
			}
		}
		/*** 完工入库 ****/
		else if (e.getSource() == btn[13]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 14) {
				int count[] = productService.updateProduct(team.getId());
				String message = "本季度完工入库：\nBeryl: " + count[0] + "个；\nCrystal: "
						+ count[1] + "个；\nRuby: " + count[2] + "个；\nSapphire: " + count[3]+"个；"+"\n请将完工产品移至对应产成品仓库";
				JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.INFORMATION_MESSAGE);
				this.changeStep();
				this.dashBoardPanel.setDashBoardData(14);
				this.dashBoardPanel.setFactoryData();
			}
		}
		/*** 投资生产线 ****/
		else if (e.getSource() == btn[14]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 15) {
				int flag=JOptionPane.showConfirmDialog(null, "本季度是否投资新生产线","提示",JOptionPane.YES_NO_CANCEL_OPTION);
				if (flag==JOptionPane.YES_OPTION){
					BuyLineDialog dialog = new BuyLineDialog(this);
					dialog.setVisible(true);
					this.changeStep();
				}
				else if(flag==JOptionPane.NO_OPTION){
					int[] tot=lineService.updateBuyLine(team.getId());
			    	if (tot[0]>=0){
			    		String message="";
			    		if(tot[1]>0)message=message+"手工线建设费用"+tot[1]+"M"+"\n";
			    		if(tot[2]>0)message=message+"半自动建设费用"+tot[2]+"M"+"\n";
			    		if(tot[3]>0)message=message+"全自动建设费用"+tot[3]+"M"+"\n";
			    		if(tot[4]>0)message=message+"柔性线建设费用"+tot[4]+"M"+"\n";
			    		JOptionPane.showMessageDialog(null, message+"本季度为建设中的生产线支出"+tot[0]+"M。\n请取现金放入对应建设中的生产线下方净值区域。", "提示",JOptionPane.INFORMATION_MESSAGE);
					    getDashBoardPanel().setFactoryData();
						getDashBoardPanel().setDashBoardData(15);
						this.changeStep();
			    	}
			    	else JOptionPane.showMessageDialog(null, "当前现金不足，请进行融资操作", "提示",JOptionPane.INFORMATION_MESSAGE);
					
			    }				
			}
		}
		/*** 生产线转产 ****/
		else if (e.getSource() == btn[15]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 16) {
				int flag=JOptionPane.showConfirmDialog(null, "本季度是否进行转产操作","提示",JOptionPane.YES_NO_CANCEL_OPTION);
				if (flag==JOptionPane.YES_OPTION){
					SwitchLineDialog dialog = new SwitchLineDialog(this);
					dialog.setVisible(true);
					this.changeStep();
					}
				else if (flag==JOptionPane.NO_OPTION){
					int tot=lineService.updateSwitchLine(team.getId());
					JOptionPane.showMessageDialog(null, "本季度完成转产"+tot+"条"+"更新实物沙盘生产区域和转产费用区域", "提示",JOptionPane.INFORMATION_MESSAGE);
					getDashBoardPanel().setFactoryData();
					getDashBoardPanel().setDashBoardData(16);	
					this.changeStep();
				}
			}
		}
		/*** 变卖生产线 ****/
		else if (e.getSource() == btn[16]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 17) {
				int flag=JOptionPane.showConfirmDialog(null, "本季度是否变卖生产线","提示",JOptionPane.YES_NO_OPTION);
				if (flag==JOptionPane.YES_OPTION){
					new SellLineDialog(this);
				}
				this.changeStep();
			}
		}
		/*** 开始下一批生产 ****/
		else if (e.getSource() == btn[17]) {

			if (Integer.parseInt(Erps.getSand().getStep()) == 18) {
				new NewProductDialog(this);				
			}
			this.changeStep();
		}

		/*** 产品研发 ****/
		else if (e.getSource() == btn[18]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 19) {
				ResearchPanel researchPanel = new ResearchPanel("Product");											
				int n = JOptionPane.showConfirmDialog(null, researchPanel,"产品研发投资", JOptionPane.OK_CANCEL_OPTION);
				if (n == JOptionPane.YES_OPTION) {
					int total = researchPanel.getTotal();
					int cash = Erps.getSand().getCash();
					if(cash>=total){
						researchPanel.payResearchFee();
						JOptionPane.showMessageDialog(null, "共支付产品研发费用"+ total + "M。\n请取现金放入沙盘产品研发对应区域","提示",JOptionPane.INFORMATION_MESSAGE);
						this.changeStep();
						this.dashBoardPanel.setDashBoardData(19);
					}else{
						JOptionPane.showMessageDialog(null, "共需支付产品研发费用"	+ total + "M\n" + "当前现金不足支付研发费用，请先融资！");						
					}					
				} else {
					this.changeStep();					
				}
			}
		}
		/*** 更新应收款 ****/
		else if (e.getSource() == btn[19]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 20) {
				JOptionPane.showMessageDialog(null, "请将沙盘应付款向现金方向挪动一格；"+"\n"+"系统盘面将在下一步自动更新。", "提示",JOptionPane.INFORMATION_MESSAGE);
				this.changeStep();
			}
		}
		/*** 应收款收现 ****/
		else if (e.getSource() == btn[20]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 21) {
				int team_Id = Erps.getCurrentTeam().getId();
				int getMoney = 0;
				int allMoney = 0;				
				TeamOrderService teamOrderService = Erps.getIocInstance().get(
						TeamOrderServiceImpl.class);
				SandService sandService = Erps.getIocInstance().get(
						SandServiceImpl.class);
				Sand sand = sandService.getSandByTeam(team_Id);
				String sysTime = sand.getTime();
				List<TeamOrder> list0 = teamOrderService
						.getTeamOrderByReceivableTime(team_Id, sysTime);

				for (TeamOrder teamOrder : list0) {
					if (!teamOrder.getStatus().equals("未交货")) {
						if(teamOrder.getTie()==(0)){
							getMoney=teamOrder.getTotal()-teamOrder.getPenalty();
							teamOrder.setStatus("已收款");
            			}
						else if(teamOrder.getTie()==-1){
            				getMoney=0;
            			}
						else{
							getMoney=teamOrder.getTie();
							teamOrder.setStatus("已收款");
						}

						allMoney += getMoney;	
						teamOrderService.updateTeamOrder(teamOrder);
					}
				}
				int cash = sand.getCash();
				sand.setCash(cash + allMoney);
				sandService.updateSand(sand);
				String message = "已成功收现应收账款共计"+allMoney+"M。"+ "\n" + "请将1Q位置应收款移至现金区。";
				JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.INFORMATION_MESSAGE);
				this.changeStep();
				this.dashBoardPanel.setDashBoardData(21);
				this.dashBoardPanel.setReceivableData();
			}
		}
		/*** 按订单交货 ****/
		else if (e.getSource() == btn[21]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 22) {
				int team_Id = Erps.getCurrentTeam().getId();
				TeamOrderService teamOrderService = Erps.getIocInstance().get(
						TeamOrderServiceImpl.class);
				SandService sandService = Erps.getIocInstance().get(
						SandServiceImpl.class);
				Sand sand = sandService.getSandByTeam(team_Id);
				String sysTime = sand.getTime();
				List<TeamOrder> list = teamOrderService
						.getTeamOrderByDeliverTime(team_Id, sysTime);
				if (list.size() > 0) {
					DeliveryDialog dialog = new DeliveryDialog(this);
					dialog.setVisible(true);
				} else {
					String message = "本季度没有需要交货的订单。";
					JOptionPane.showMessageDialog(null, message, "提示",
							JOptionPane.INFORMATION_MESSAGE);
				}
				this.changeStep();
				this.dashBoardPanel.setDashBoardData(22);
			}
		}
		/*** 支付行政管理费 ****/
		else if (e.getSource() == btn[22]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 23) {
				int currentQuarter = CalculateQuarter.getCurrentQuarter(Erps
						.getSand().getTime());
				Sand sand = Erps.getSand();
				int cash = sand.getCash();
				int managementFee = sand.getManagementFee();
				String time = sand.getTime();
				if (currentQuarter == 4) {
					sand.setCash(cash - 1);
					sand.setManagementFee(managementFee + 1);
					sandService.updateSand(sand);
					this.changeStep();
				} else {
					sand.setCash(cash - 1);
					sand.setManagementFee(managementFee + 1);
					sand.setTime(CalculateQuarter.addOneQuarter(time));
					sand.setStep("5");
					sandService.updateSand(sand);
					this.btn[22].setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.normal));
					this.btn[4].setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.green));
				}
				JOptionPane.showMessageDialog(null, "已支付行政管理费1M"+"\n"+"请从现金区域取1M放入管理费区域", "提示",JOptionPane.INFORMATION_MESSAGE);
				this.schedule.setSeheduleData();
				this.dashBoardPanel.setDashBoardData(23);
			}
		}

		/*** 更新长贷 ****/
		else if (e.getSource() == btn[23]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 24) {
				JOptionPane.showMessageDialog(null, "请将沙盘长贷区域贷款向现金方向移动一格；"+"\n"+"系统盘面将在下一步自动更新。", "提示",
						JOptionPane.INFORMATION_MESSAGE);
				this.changeStep();
			}
		}
		/*** 偿还长贷 ****/
		else if (e.getSource() == btn[24]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 25) {
				int i = loanService.getLoans(Erps.getCurrentTeam().getId(),"长贷", "已审核").size();
				int j = loanService.getReturnLoans(Erps.getCurrentTeam().getId(), "长贷").size();
				if (i > 0) {
					Sand tempSand1 = sandService.getSandByTeam(team.getId());
					int tempCash1=tempSand1.getCash();
					int tempInterset1=tempSand1.getInterest();
					if (loanService.repayLongLoan(team.getId())) {
						Sand tempSand2 = sandService.getSandByTeam(team.getId());
						int tempCash2=tempSand2.getCash();
						int tempInterset2=tempSand2.getInterest();
						int interest=tempInterset2-tempInterset1;
						String message = "共支付"+i+"笔长贷利息"+interest+"M。"+"\n共偿还"+j+"笔长贷"+(tempCash1-tempCash2-interest)+"M。";						
						JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.INFORMATION_MESSAGE);
						this.changeStep();
						this.dashBoardPanel.setDashBoardData(25);
						this.dashBoardPanel.setLongLoanData();
					} else {
						JOptionPane.showMessageDialog(null,"当前现金不足以偿还长贷和付息，请先融资！","警告",JOptionPane.WARNING_MESSAGE);
					}
				} else {
					JOptionPane.showMessageDialog(null, "当前没有长贷", "提示",JOptionPane.INFORMATION_MESSAGE);
			        this.changeStep();
			    }
			}
		}
		/*** 申请长贷 ****/
		else if (e.getSource() == btn[25]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 26) {
				int availiable=loanService.getAvailiable();
				if(availiable>=10){
					JComboBox<String> amountCombo = new JComboBox<String>();
					for (int i=1;i<=12;i++)	{
						int temp=i*10;
						if (temp<=availiable){
							amountCombo.addItem(temp+"");
						}
						else
							break;
					}
					String[] year = { "1Y", "2Y", "3Y", "4Y" };
					JPanel panel = new JPanel();				
					JComboBox<String> yearCombo = new JComboBox<String>(year);
					panel.add(amountCombo);
					panel.add(yearCombo);
					JPanel loanPanel = new JPanel(new BorderLayout());
					JPanel labelPanel=new  JPanel(new BorderLayout());
					labelPanel.add(new JLabel("目前可贷款数量:"+availiable+"M"), BorderLayout.NORTH);
					labelPanel.add(new JLabel("请选择需要长贷金额和年限?"), BorderLayout.CENTER);
					loanPanel.add(labelPanel, BorderLayout.CENTER);
					loanPanel.add(panel, BorderLayout.SOUTH);
					int n = JOptionPane.showConfirmDialog(null, loanPanel,
							"申请长期贷款", JOptionPane.OK_CANCEL_OPTION);
					if (n == JOptionPane.YES_OPTION) {
						String s = (String) amountCombo.getSelectedItem();
						int y = yearCombo.getSelectedIndex() + 1;						
						if(s!=null){
							if(loanService.ifAvailable(Integer.parseInt(s))){
							loanService.applyLongLoan(Integer.parseInt(s), y);
							String info = "申请"+Integer.parseInt(s)+"M长期贷款成功，请前往银行领取现金！";
							JOptionPane.showMessageDialog(null, info, "提醒",
									JOptionPane.INFORMATION_MESSAGE);
							}
							else{
								JOptionPane.showMessageDialog(null, "贷款总额超过所有者权益的2倍，无法贷款", "提醒",
										JOptionPane.INFORMATION_MESSAGE);
							}
						}
						else{
							JOptionPane.showMessageDialog(null, "没有剩余可贷款金额", "提醒",
									JOptionPane.INFORMATION_MESSAGE);
						}
					}
				}else{
					JOptionPane.showMessageDialog(null, "可申请长贷额度小于10M，不能申请。", "提醒",JOptionPane.INFORMATION_MESSAGE);
				}				
				this.changeStep();
				this.dashBoardPanel.setDashBoardData(26);
				this.dashBoardPanel.setLongLoanData();
			}
		}


		/*** 支付设备维修费 ****/
		else if (e.getSource() == btn[26]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 27) {
				int pay = lineService.repairLine(team.getId());
				if (pay >= 0) {
					JOptionPane.showMessageDialog(null, "本年度已支付生产线维护费" + pay
							+ "M"+"\n"+"请从沙盘现金区域取"+pay+"M放入维修费区域"+"\n未使用生产线不需要支付维修费。", "提示", JOptionPane.INFORMATION_MESSAGE);
					this.changeStep();
					this.dashBoardPanel.setDashBoardData(27);
				} else
					JOptionPane.showMessageDialog(null, "现金不足请进行融资操作", "提示",JOptionPane.INFORMATION_MESSAGE);
			}
			this.dashBoardPanel.setLongLoanData();    //更新长贷面板 防止工作人员审批较慢导致的面板数据不符
			
		}

		/*** 支付租金 ****/
		else if (e.getSource() == btn[27]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 28) {
				int pay = factoryService.payRentFactoy(team.getId());
				if (pay >= 0) {
					String message = "本年度应支付租金合计"+pay +"M。"+"\n"+"请从沙盘现金区域取"+pay+"M放入租金区域";
					JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.INFORMATION_MESSAGE);
					this.changeStep(); 
					this.dashBoardPanel.setDashBoardData(28);
				} else
					JOptionPane.showMessageDialog(null, "当前现金不足，请先进行融资操作",	"提示", JOptionPane.INFORMATION_MESSAGE);
			}
		}

		/*** 折旧 ****/
		else if (e.getSource() == btn[28]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 29) {
				int depreciateLine=lineService.depreciateLine(team.getId());
				String message = "本年度生产线应提取折旧合计"+depreciateLine+"M。"+"\n请从每条生产线下方净值区域取对应折旧费放入折旧区域";
				JOptionPane.showMessageDialog(null, message, "提示",JOptionPane.INFORMATION_MESSAGE);
				this.changeStep();
				this.dashBoardPanel.setDashBoardData(29);
				this.dashBoardPanel.setFactoryData();
			}
		}

		/*** 市场开拓 ****/
		else if (e.getSource() == btn[29]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 30) {
				ResearchPanel researchPanel = new ResearchPanel("Market");
				int n = JOptionPane.showConfirmDialog(null, researchPanel,
						"市场开拓投资", JOptionPane.OK_CANCEL_OPTION);
				if (n == JOptionPane.YES_OPTION) {
					int total = researchPanel.getTotal();
					int cash = Erps.getSand().getCash();
					if (cash >= total) {
						researchPanel.payResearchFee();
						JOptionPane.showMessageDialog(null, "共支付市场开拓费用" + total	+ "M。\n请取现金放入沙盘市场开拓对应区域");
						this.changeStep();
						this.dashBoardPanel.setDashBoardData(30);						
					}else{
						JOptionPane.showMessageDialog(null, "共需支付开拓市场费用"	+ total + "M\n" + "当前现金不足支付费用，请先融资！");
					}					
				} else {
					this.changeStep();
				}
			}

		}

		/*** ISO认证 ****/
		else if (e.getSource() == btn[30]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 31) {
				ResearchPanel researchPanel = new ResearchPanel("ISO");
				int n = JOptionPane.showConfirmDialog(null, researchPanel,"ISO认证投资", JOptionPane.OK_CANCEL_OPTION);
				if (n == JOptionPane.YES_OPTION) {
					int total = researchPanel.getTotal();
					int cash = Erps.getSand().getCash();
					if (cash >= total) {
						researchPanel.payResearchFee();
						JOptionPane.showMessageDialog(null, "共支付ISO认证费用"+ total + "M。\n请取现金放入沙盘ISO认证对应区域");
						this.changeStep();
						this.dashBoardPanel.setDashBoardData(31);						
					} else {
						JOptionPane.showMessageDialog(null, "共需支付ISO认证费用"+ total + "M\n" + "当前现金不足支付费用，请先融资！");						
					}					
				} else {
					this.changeStep();
				}
			}
		}
		/*** 关账 ****/
		else if (e.getSource() == btn[31]) {
			if (Integer.parseInt(Erps.getSand().getStep()) == 32) {
				int team_Id = Erps.getCurrentTeam().getId();

				// 开始统计报表
				ResearchService researchService = Erps.getIocInstance().get(
						ResearchServiceImpl.class);
				SandService sandService = Erps.getIocInstance().get(
						SandServiceImpl.class);
				ComprehensivefeeService comprehensivefeeService = Erps
						.getIocInstance()
						.get(ComprehensivefeeServiceImpl.class);
				TeamOrderService teamOrderService = Erps.getIocInstance().get(
						TeamOrderServiceImpl.class);
				ProductService productService = Erps.getIocInstance().get(
						ProductServiceImpl.class);
				List<Research> list = researchService
						.getMaterial(team_Id, null);
				List<TeamOrder> list1 = teamOrderService
						.getTeamOrderByDeliverTime(team_Id, null);
				Sand sand1 = sandService.getSandByTeam(team_Id);
				List<Comprehensivefee> comprehensivefeeList = comprehensivefeeService
						.getComprehensivefee(team_Id, "Y"
								+ sand1.getTime().charAt(1));
				Comprehensivefee comprehensivefee = comprehensivefeeList.get(0);
				// 更新综合费用表
				int managementFee = 0, advertisingFee = 0, maintenanceFee = 0, switchFee = 0, rent = 0,  other = 0, product = 0, market = 0, iso = 0, total = 0;

				managementFee = sand1.getManagementFee();// 管理费
				advertisingFee = sand1.getAdvertisingFee();// 广告费
				maintenanceFee = sand1.getMaintenanceFee();// 维修费
				switchFee = sand1.getSwitchFee();// 转产费
				rent = sand1.getRent();// 租金
				other = sand1.getOther();// 其他费用

				for (Research research : list) {
					if (research.getTime().charAt(1) == sand1.getTime().charAt(
							1)) {
						if (research.getName().equals("产品研发"))// 产品研发费用
							product += research.getAmount();
						if (research.getName().equals("市场开拓"))// 市场开拓费用
							market += research.getAmount();
						if (research.getName().equals("ISO认证"))// ISO认证费用
							iso += research.getAmount();
					}
				}

				total = managementFee + advertisingFee + maintenanceFee
						+ switchFee + rent + other + product + market + iso;// 合计
				comprehensivefee.setManagementFee(managementFee);
				comprehensivefee.setAdvertisingFee(advertisingFee);
				comprehensivefee.setMaintenanceFee(maintenanceFee);
				comprehensivefee.setSwitchFee(switchFee);
				comprehensivefee.setRent(rent);
				comprehensivefee.setResearch(product);
				comprehensivefee.setMarketFee(market);
				comprehensivefee.setIso(iso);
				comprehensivefee.setOther(other);
				comprehensivefee.setTotal(total);
				comprehensivefeeService
						.updateComprehensivefee(comprehensivefee);// 更新综合费用表
				// 更新损益表
				IncomestatementService incomestatementService = Erps
						.getIocInstance().get(IncomestatementServiceImpl.class);
				BalancesheetService balancesheetService = Erps.getIocInstance()
						.get(BalancesheetServiceImpl.class);
				List<Balancesheet> oldBalancesheetList = balancesheetService
						.getBalancesheetOfLastYear(team_Id, sand1.getTime());
				FreeMarketService freeMarketService = Erps.getIocInstance().get(FreeMarketServiceImpl.class);
				List<FreeMarket> freeMarketList = freeMarketService.getBuyerMseeage(team_Id);
				int saleIncome = 0, cost = 0, grossMargin = 0, comprehensiveCost = 0, depreciation = 0, financial = 0, operatingProfit = 0, extraProfit = 0, allProfit = 0, incomeTax = 0, netProfit = 0;// 当年损益表数据
				int saveNetProfit = oldBalancesheetList.get(0)
						.getTotal_oldProfit()
						+ oldBalancesheetList.get(0).getNetProfit();

				for(FreeMarket freeMarket:freeMarketList){
					/**
					if(freeMarket.getType().equals("Material")&&freeMarket.getBuyer()!=0){
						saleIncome += freeMarket.getPrice();
						cost += freeMarket.getNum();
					}else 
					*/
					if(freeMarket.getType().equals("Product")&&freeMarket.getBuyer()!=0){
						Product saleProduct = productService.getProductByID(freeMarket.getNote());
						saleIncome += freeMarket.getPrice();
						cost += saleProduct.getCost();
					}
				}
				for (TeamOrder teamOrder : list1) {// 获取当年已收款订单的总收入额以及成本
					if ((teamOrder.getDeliver().charAt(1) + "").equals(sand1
							.getTime().charAt(1) + "")) {
						saleIncome += (teamOrder.getTotal() - teamOrder
								.getPenalty());
						cost = cost + teamOrder.getCost();
					}
				}
				grossMargin = saleIncome - cost;// 算出毛利
				comprehensiveCost = total;// 获取综合费用
				depreciation = sand1.getDepreciation();// 算取当年生产线折旧费用
				financial = sand1.getInterest() + sand1.getDiscount();// 获取当年财务净损益
				operatingProfit = grossMargin - comprehensiveCost
						- depreciation - financial;// 算取营业利润
				extraProfit = sand1.getNon_operating_Income();// 营业外收入
				allProfit = operatingProfit + extraProfit;// 利润总额
				if (saveNetProfit > 0 && allProfit > 0)
					incomeTax = Integer
							.parseInt(new BigDecimal(allProfit * 0.3).setScale(
									0, BigDecimal.ROUND_HALF_UP) + "");
				else if (saveNetProfit < 0 && (saveNetProfit + allProfit) > 0)
					incomeTax = Integer.parseInt(new BigDecimal(
							((saveNetProfit + allProfit) * 0.3)).setScale(0,
							BigDecimal.ROUND_HALF_UP)
							+ "");
				else if (allProfit < 0 || (saveNetProfit + allProfit) < 0)
					incomeTax = 0;// 个人所得税
				netProfit = allProfit - incomeTax;// 算取净利润

				List<Incomestatement> thisIncomestatementList = incomestatementService
						.getIncomestatementOfThisYear(team_Id, sand1.getTime());
				Incomestatement thisIncomestatement = thisIncomestatementList
						.get(0);
				thisIncomestatement.setIncome(saleIncome);
				thisIncomestatement.setCost(cost);
				thisIncomestatement.setGrossprofit(grossMargin);
				thisIncomestatement.setComprehensiveFee(comprehensiveCost);
				thisIncomestatement.setDepreciation(depreciation);
				thisIncomestatement.setNet_profit_loss(financial);
				thisIncomestatement.setProfit(operatingProfit);
				thisIncomestatement.setExtroIncome(extraProfit);
				thisIncomestatement.setTotalProfit(allProfit);
				thisIncomestatement.setTax(incomeTax);
				thisIncomestatement.setNetProfit(netProfit);
				incomestatementService
						.updateIncomestatement(thisIncomestatement);// 更新今年损益表

				// 资产负债表
				int cash = 0, short_termLoan = 0, receivable = 0, payable = 0, materialNumber = 0, finishedProduct = 0, long_termLoan = 0, productInProcess = 0, totalCurrentasset = 0, totalLoan = 0, factoryValue = 0, capital = 0, lineValue1 = 0, lineValue2 = 0, totalFixedasset = 0, totalEquity = 0, totalAsset = 0, total_equityAndLoan = 0;// 当年资产负债表的数据
				StoreService storeService = Erps.getIocInstance().get(
						StoreServiceImpl.class);
				Store store = storeService.getStoreByTeamId(team_Id);
				List<Product> list3 = productService.getProductByTypeAndStatus(
						team_Id, null, "成品");
				List<Product> list4 = productService.getProductByTypeAndStatus(
						team_Id, null, "在制品");

				LineService lineService = Erps.getIocInstance().get(
						LineServiceImpl.class);
				List<Line> list5 = lineService.getLineByTeamId(team_Id);
				FactoryService factoryService = Erps.getIocInstance().get(
						FactoryServiceImpl.class);
				List<Factory> list6 = factoryService.getFactoyByTeamId(team_Id);
				MaterialService materialService = Erps.getIocInstance().get(
						MaterialServiceImpl.class);
				List<Material> list7 = materialService.getGetMaterialOrder(
						team_Id, null);
				List<Loan> list8 = loanService.getLoans(team_Id, null, "已审核");
				cash = sand1.getCash();// 获取现金
				for (Loan loan : list8) {
					if (loan.getLoanType().equals("短贷")|| loan.getLoanType().equals("高利贷"))// 短期负债
						short_termLoan += loan.getAmount();
					if (loan.getLoanType().equals("长贷"))// 长期负债
						long_termLoan += loan.getAmount();
				}
				for (TeamOrder teamOrder : list1) {// 应收款
					if (teamOrder.getStatus().equals("已交货")) {
						int getMoney = teamOrder.getTotal()
								- teamOrder.getPenalty();
						receivable += getMoney;
					}
				}

				for (Material material : list7) {// 应付账款
					if ((material.getGetTime().charAt(1) + "").equals(sand1
							.getTime().charAt(1) + "")
							&& material.getStatus().equals("已入库"))
						payable += material.getNumber();
				}

				materialNumber = store.getM1() + store.getM2() + store.getM3()
						+ store.getM4();// 获取原材料数

				for (Product productValue1 : list3) {// 成品价值
					finishedProduct = finishedProduct + productValue1.getCost();
				}
				for (Product productValue2 : list4) {// 在制品价值
					productInProcess = productInProcess
							+ productValue2.getCost();
				}
				totalCurrentasset = cash + receivable + materialNumber
						+ finishedProduct + productInProcess;// 流动资产合计
				totalLoan = short_termLoan + payable + incomeTax
						+ long_termLoan;// 负债合计
				for (Factory factory : list6) {// 获取土地建筑
					if (factory.getType().equals("大厂房")
							&& factory.getStatus().equals("已购买"))
						factoryValue += 40;
					if (factory.getType().equals("中厂房")
							&& factory.getStatus().equals("已购买"))
						factoryValue += 30;
					if (factory.getType().equals("小厂房")
							&& factory.getStatus().equals("已购买"))
						factoryValue += 15;
				}
				capital = 50;// 股东资本固定为 50
				for (Line line : list5) {// 获取已有生产线价值
					if (line.getStatus().equals("全新")
							|| line.getStatus().equals("转产")
							|| line.getStatus().equals("生产")
							|| line.getStatus().equals("空闲")) {
						lineValue1 += line.getValue();
					}
					if (line.getStatus().equals("在建")) {// 获取在建生产线价值
						lineValue2 += line.getValue();
					}
				}
				// saveNetProfit是以前年度利润
				// netProfit;是 损益表里的净利润直接调用
				totalFixedasset = factoryValue + lineValue1 + lineValue2;// 固定资产合计
				totalEquity = capital + saveNetProfit + netProfit;// 所有者权益合计
				totalAsset = totalCurrentasset + totalFixedasset;// 资产总计
				total_equityAndLoan = totalLoan + totalEquity;// 负债及权益合计
				List<Balancesheet> thisBalancesheetList = balancesheetService
						.getBalancesheetOfThisYear(team_Id, sand1.getTime());
				Balancesheet thisBalancesheet = thisBalancesheetList.get(0);
				thisBalancesheet.setCash(cash);
				thisBalancesheet.setShort_termLoan(short_termLoan);
				thisBalancesheet.setReceivable(receivable);
				thisBalancesheet.setPayable(payable);
				thisBalancesheet.setMaterial(materialNumber);
				thisBalancesheet.setTax(incomeTax);
				thisBalancesheet.setFinishedProduct(finishedProduct);
				thisBalancesheet.setLong_termLoan(long_termLoan);
				thisBalancesheet.setProductInProcess(productInProcess);
				thisBalancesheet.setTotalCurrentAsset(totalCurrentasset);
				thisBalancesheet.setTotalLoan(totalLoan);
				thisBalancesheet.setFactory(factoryValue);
				thisBalancesheet.setCapital(capital);
				thisBalancesheet.setLine(lineValue1);
				thisBalancesheet.setTotal_oldProfit(saveNetProfit);
				thisBalancesheet.setLineInProcess(lineValue2);
				thisBalancesheet.setNetProfit(netProfit);
				thisBalancesheet.setTotalFixedAsset(totalFixedasset);
				thisBalancesheet.setTotalEquity(totalEquity);
				thisBalancesheet.setTotalAsset(totalAsset);
				thisBalancesheet.setTotal_equityAndLoan(total_equityAndLoan);
				balancesheetService.updateBalancesheet(thisBalancesheet);// 更新当年资产负债表

				// 跟新小组成绩
				// 判断第一次破产时间
				ScoreService scoreService = Erps.getIocInstance().get(
						ScoreServiceImpl.class);
				List<Loan> usuriousLoan = loanService.getLoans(team_Id, "高利贷",
						"已审核");
				ExtrascoreService extrascoreService = Erps.getIocInstance().get(
						ExtrascoreServiceImpl.class);
				List<Extrascore> getExrascore = extrascoreService.getExtrascore(team_Id, sand1.getTime());
				Extrascore thisExtrascore = getExrascore.get(0);
				List<Score> scoreList = scoreService.getScore(team_Id);
				Score thisScore = scoreList.get(0);
				String bankruptYear = sand1.getTime();
				if (usuriousLoan.size() > 0) {// 该小组今年有破产记录
					for (Loan usuriousloan : usuriousLoan) {
						if (usuriousloan.getBeginTime().compareTo(bankruptYear) < 0)
							bankruptYear = usuriousloan.getBeginTime();
					}
				}
				if (totalEquity < 0 || usuriousLoan.size() > 0)// 如果有破产情况，跟新破产时间
					if (thisScore.getBankrupt().equals("未破产")) {// 若该小组先前已破产，则不改时间
						thisScore.setBankrupt(bankruptYear);
					}
				// 计算发展指数
				int factory = 0, line = 0, research = 0, Iso = 0, markets = 0;
				// 计算工程发展指数
				for (Factory factorys : list6) {
					if (factorys.getType().equals("大厂房")
							&& factorys.getStatus().equals("已购买"))
						factory += 40;
					if (factorys.getType().equals("中厂房")
							&& factorys.getStatus().equals("已购买"))
						factory += 30;
					if (factorys.getType().equals("小厂房")
							&& factorys.getStatus().equals("已购买"))
						factory += 20;
				}
				// 计算生产线发展指数
				for (Line lines : list5) {
					if (lines.getType().equals("手工线")&&(!lines.getStatus().equals("空置")))
						line += 5;
					if (lines.getType().equals("半自动")&&(!lines.getStatus().equals("空置")))
						line += 10;
					if (lines.getType().equals("全自动")&&(!lines.getStatus().equals("空置")))
						line += 15;
					if (lines.getType().equals("柔性线")&&(!lines.getStatus().equals("空置")))
						line += 20;
				}
				// 计算研发发展指数
				if (researchService.findResearchs(team_Id, "Crystal") == 4)
					research += 20;
				if (researchService.findResearchs(team_Id, "Ruby") == 6)
					research += 30;
				if (researchService.findResearchs(team_Id, "Saphire") == 8)
					research += 40;
				if (researchService.findResearchs(team_Id, "ISO9000") == 1)
					Iso += 15;
				if (researchService.findResearchs(team_Id, "ISO14000") == 2)
					Iso += 30;
				if (researchService.findResearchs(team_Id, "区域") == 1)
					markets += 10;
				if (researchService.findResearchs(team_Id, "国内") == 2)
					markets += 20;
				if (researchService.findResearchs(team_Id, "亚洲") == 3)
					markets += 30;
				if (researchService.findResearchs(team_Id, "国际") == 4)
					markets += 40;
				// 计算综合得分
				int developmentPotential = factory + line + research + Iso + markets;
				int totalPoint =(int) (totalEquity*Math.ceil((1 + developmentPotential / 100.0)));
				thisExtrascore.setAvgort(totalPoint);
				thisExtrascore.setDevelopmentPotential(developmentPotential);
				thisExtrascore.setProductionCapacity(line);
				thisExtrascore.setResearchAbility(research + Iso + markets);
				thisScore.setScore(totalPoint);
				thisScore.setTotalEquity(totalEquity);
				scoreService.updateScore(thisScore);
				extrascoreService.updateExtrascore(thisExtrascore);

				Sand sand = Erps.getSand();
				sand.setStep("1");
				sand.setTime(CalculateQuarter.addOneQuarter(Erps.getSand()
						.getTime()));
				sandService.updateSand(sand);
				this.schedule.setSeheduleData();
				this.btn[31].setUI(new BEButtonUI()
						.setNormalColor(BEButtonUI.NormalColor.normal));
				this.btn[0].setUI(new BEButtonUI()
						.setNormalColor(BEButtonUI.NormalColor.green));
				JOptionPane.showMessageDialog(null, "系统关账成功！请在我的报表中查看本年度财务报告。", "提示",JOptionPane.INFORMATION_MESSAGE);
			}
		}
	}

	public SandPanel getDashBoardPanel() {
		return dashBoardPanel;
	}
}
